/*******************************************************
  > Copyright (C) 2024 ==iot== All rights reserved.
  > File Name: 2---server.c
  > Author: wyf
  > Created Time: 2024年08月13日 星期二 12时15分45秒
 ***************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h> //目录名获取配合DIR
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h> //文件控制操作
#include <sys/types.h> //获取pid等
#include <sys/wait.h> //等待子进程结束
#include <time.h> //时间获取
#include <sys/ipc.h> //进程通信
#include <sys/msg.h> //消息队列
#include <sys/shm.h> //共享内存
#include <signal.h> //信号处理
#include <pthread.h> //线程
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

//   1、开发一个计算服务器，能够计算两个整数的加减乘除
//字符串格式：##add#23#12##



int main(int argc, const char* argv[])
{
	char buf[1024] = { 0 };
	//创建套接字
	int sock = 0;
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock == -1) {
		perror("socket");
	}

	int ret = 0;
	int number1 = 0;
	int number2 = 0;
	int result = 0;
	//绑定地址
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = 5493;
	addr.sin_addr.s_addr = inet_addr("192.168.48.128");
	bind(sock, (struct sockaddr*)&addr, sizeof(addr));

	//接收客户端的信息
	struct sockaddr_in client;
	int len = sizeof(client);
	
	ret = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&client, &len);
	if (ret == -1) {
		perror("recvfrom");
	}
	printf("buf = %s\n", buf);

	if (strncmp(buf, "##add", 5) == 0) {//加
		sscanf(buf + 5, "#%d#%d##", &number1, &number2);
		printf("number1 = %d\n", number1);
		printf("number2 = %d\n", number2);
		result = number1 + number2;
		printf("result = %d\n", result);
		ret = sendto(sock, &result, sizeof(result), 0, (struct sockaddr*)&client, len);
	}
	else if (strncmp(buf, "##che", 5) == 0) {//乘
		sscanf(buf + 5, "#%d#%d##", &number1, &number2);
		printf("number1 = %d\n", number1);
		printf("number2 = %d\n", number2);
		result = (number1 * number2);
		printf("result = %d\n", result);
		ret = sendto(sock, &result, sizeof(result), 0, (struct sockaddr*)&client, len);
	}
	else if (strncmp(buf, "##sub", 5) == 0) {//减
		sscanf(buf + 5, "#%d#%d##", &number1, &number2);
		printf("number1 = %d\n", number1);
		printf("number2 = %d\n", number2);
		result = (number1 - number2);
		printf("result = %d\n", result);
		ret = sendto(sock, &result, sizeof(result), 0, (struct sockaddr*)&client, len);
	}
	else if (strncmp(buf, "##div", 5) == 0) {//除
		sscanf(buf + 5, "#%d#%d##", &number1, &number2);
		printf("number1 = %d\n", number1);
		printf("number2 = %d\n", number2);
		result = (number1 / number2);
		printf("result = %d\n", result);
		ret = sendto(sock, &result, sizeof(result), 0, (struct sockaddr*)&client, len);
	}

	close(sock);

	return 0;

}




